<?php
/**
 * API file
 * @author Izumi-kun
 */

$start = microtime();
error_reporting(0);
set_time_limit(60);
$debug = false;

if ($debug){
    error_reporting(E_ALL);
    echo '
        <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
        <html xmlns="http://www.w3.org/1999/xhtml">
        <head>
            <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
            <meta name="description" content="degug" />
            <meta name="keywords" content="Danbooru, batch, links, download" />
            <title>Danbooru link grabber Core File</title></head>
        <body>';
}

include_once('Classes/DanbooruLinkGrabber.php');
$dlg = new DanbooruLinkGrabber();
$dlg->workDir = dirname(__FILE__);
$dlg->noCache = false;

$dlg->initRequest($_POST['site'], $_POST['tags'], $_POST['limit'], $_POST['page'], $_POST['user'], $_POST['pass']);

//いただきます! if
if (!$dlg->processRequest()){
    echo '<div align="left">Some problems occurred. Read text below for more info.';
    echo '<pre>' . $dlg->getDebugMsg() . '</pre></div>';
    die;
}

$info = $dlg->getRequestInfo();

if ($debug){
    echo '
<pre>
------------------------------------------------------------------------------------------------------------------------
'.$info['site'].'
Debug mode
------------------------------------------------------------------------------------------------------------------------
</pre>';
}

echo '
    <b>' . $info['totalLinks'] . '</b> files found! ' ,
    $info['totalSize'] ? 'Total size: <b>' . round($info['totalSize'] / 1024 / 1024, 2) . '</b> MiB.' : 'Total size of files can not be counted.' , '
    <div align="left">
        <a onclick="document.getElementById(\'links\').focus();document.getElementById(\'links\').select();" href="#">Select All</a>
    </div>
    <textarea readonly="readonly" id="links" align="left" style="background-color: #444; border: 1px solid #bbb; font: 8pt Courier New; width: 100%; height: 300px; overflow: auto; white-space: nowrap;">' . $dlg->getLinks() . '</textarea>
';

$time = round(array_sum(explode(' ', microtime())) - array_sum(explode(' ', $start)), 3);
$mem = round(memory_get_peak_usage() / 1024 / 1024, 2);
echo '<div class="debug">time: ' . $time . 's, mem: ' . $mem . 'm</div>';

if ($debug){
    echo '
<div align="left">
<pre>
' . $dlg->getDebugMsg() . '
========================================================================================================================
</pre>
</div>
</body>
</html>';
}

